<template>
  <n-data-table
    v-model:checked-row-keys="state.dept.checkedRowKeys"
    striped
    :row-key="(row) => `${row.deptId}`"
    :columns="deptColumns"
    :data="state.dept.list"
    :pagination="pagination.dept"
    :max-height="props.height - 80"
    @update:checked-row-keys="onDeptUpdate"
  />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { deptApi } from '@/api/modules/dept'

  const props = withDefaults(defineProps<{ height: number; multiple?: boolean }>(), {
    multiple: true
  })
  const emits = defineEmits(['select', 'selectSingle'])

  const state = reactive({
    dept: { list: [] as any[], checkedRowKeys: [] as any[] }
  })

  const deptColumns = [
    {
      type: 'selection',
      multiple: props.multiple
    },
    { title: '部门编号', key: 'deptCode' },
    { title: '部门名称', key: 'deptName' }
  ]

  const pagination = reactive({
    dept: {
      page: 1,
      pageSize: 30,
      showSizePicker: true,
      pageSizes: [10, 30, 50, 100],
      onChange: (page: number) => {
        pagination.dept.page = page
        findDeptList()
      },
      onUpdatePageSize: (pageSize: number) => {
        pagination.dept.pageSize = pageSize
        pagination.dept.page = 1
        findDeptList()
      }
    }
  })

  onMounted(() => {
    findDeptList()
  })

  const findDeptList = () => {
    const params = { pageNum: pagination.dept.page, pageSize: pagination.dept.pageSize }
    deptApi.findListPage(params).then((resp: any) => {
      if (resp.success) {
        state.dept.list = resp.data.list
      }
    })
  }

  const onDeptUpdate = (
    keys: Array<string | number>,
    rows: object[],
    meta: { row: object | undefined; action: 'check' | 'uncheck' | 'checkAll' | 'uncheckAll' }
  ) => {
    let ids = ''
    rows.forEach((r: any) => {
      ids += "'" + r.deptId + "',"
    })
    if (ids) {
      ids = ids.substring(0, ids.length - 1)
    }
    const exp = '${flowCandidateUsers.getByDept(' + ids + ')}'
    emits('select', [{ id: exp }])
    emits('selectSingle', rows[0])
  }
</script>

<style lang="scss" scoped></style>
